//
//  YCGoodsSortViewController.m
//  lianganyuchu
//
//  Created by iMac on 17/3/2.
//  Copyright © 2017年 杭州桑缇电子商务有限公司. All rights reserved.
//

#import "YCGoodsSortViewController.h"
#define YCSortCellIdentify @"YCSortTableViewCell"
#define YCGoodsSortCellIdentify @"YCGoodsSortTableViewCell"

@interface YCGoodsSortViewController ()
{
    UITableView *m_leftTableView;
    UITableView *m_tableView;
    NSInteger _selectIndex;
    
    NSMutableArray *m_arraySorts;
    YCStockAlertView *m_alertView;
    
    NSArray *_selectArray;
    BOOL _isSaveBtn;
}
@end

@implementation YCGoodsSortViewController
-(void)viewWillAppear:(BOOL)animated
{
    [_naviVC setNaviHidden:NO];
    [_naviVC setMainNaviVC];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"商品排序";
    self.navigationItem.leftBarButtonItem=[self tbarBackButtonWhite];
    
    _selectIndex=0;
    [self addMianView];
    [self loadData];
}
-(void)goBack
{
    ItemSortTable *sort=m_arraySorts[_selectIndex];
    if (sort.items==_selectArray) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self showAlertView];
    }
}
-(void)showAlertView
{
    if (m_alertView==nil) {
        m_alertView=[[YCStockAlertView alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width, kMainScreen_Height)];
    }
    [m_alertView showSaveAlert:@"是否保存排序?"];
    m_alertView.cancelBlock=^(){
        [self.navigationController popViewControllerAnimated:YES];
    };
    m_alertView.saveBlock=^(){
        _isSaveBtn=NO;
        [self loadSaveData];
    };
    [self.view.window addSubview:m_alertView];
}
-(void)loadData
{
    ShopItemIndexRequest *request = [ShopItemIndexRequest new];
    [apiClient hideProgress];
    [apiClient disableAfterRequest];
    [apiClient doShopItemIndex:request success:^(ApiResponse *data, NSString *url) {
        ShopItemIndexResponse *response=[[ShopItemIndexResponse alloc]initWithCGResponse:data];
        m_arraySorts=[NSMutableArray arrayWithArray:response.list];
        
        [m_leftTableView reloadData];
        
        ItemSortTable *sort=m_arraySorts[_selectIndex];
        _selectArray=sort.items;
        m_tableView.layer.shadowPath=nil;
        m_tableView.layer.shadowOpacity=0;        
        CGFloat tableW=kMainScreen_Width-50-25;
        [m_tableView setFrame:CGRectMake(60, kNAV_HEIGHT+kDistance, tableW, sort.items.count*50)];
        [m_tableView addShadow];
        [m_tableView reloadData];
    }failure:^(ApiResponse *data, NSString *url){
    }];
}
-(void)addMianView
{
    [self.view setBackgroundColor:WHITE_COLOR];
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont LightFontOfSize:15]];
    [rightBtn addTarget:self action:@selector(btnSaveClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

    
    m_leftTableView=[[UITableView alloc]init];
    m_leftTableView.backgroundColor=BACK_COLOR;
    m_leftTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    m_leftTableView.delegate=self;
    m_leftTableView.dataSource=self;
    m_leftTableView.bounces=NO;
    [self.view addSubview:m_leftTableView];
    [m_leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.width.mas_equalTo(50);
        make.top.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view).offset(0);
    }];
    [m_leftTableView registerNib:[UINib nibWithNibName:YCSortCellIdentify bundle:nil] forCellReuseIdentifier:YCSortCellIdentify];
    
    
    m_tableView=[[UITableView alloc]init];
    [m_tableView setBackgroundColor:WHITE_COLOR];
    m_tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    m_tableView.delegate=self;
    m_tableView.dataSource=self;
    m_tableView.bounces=NO;
    m_tableView.clipsToBounds = NO;
    [self.view addSubview:m_tableView];
    [m_tableView registerNib:[UINib nibWithNibName:YCGoodsSortCellIdentify bundle:nil] forCellReuseIdentifier:YCGoodsSortCellIdentify];
    
    [m_tableView setEditing:YES animated:YES];
    
}
#pragma mark tableview datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView==m_leftTableView) {
        return 1;
    }
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==m_leftTableView) {
        return m_arraySorts.count;
    }else{
        ItemSortTable *sort=m_arraySorts[_selectIndex];
        return sort.items.count;
    }
}
#pragma mark tableview delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==m_leftTableView) {
        ItemSortTable *site=m_arraySorts[indexPath.row];
        CGFloat height=getTextSize(site.title, 35, [UIFont LightFontOfSize:14]).height-45;
        return 70+height;
    }
    return 50;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (nil == cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    if (tableView==m_leftTableView) {
        YCSortTableViewCell *_cell = (YCSortTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCSortCellIdentify forIndexPath:indexPath];
        if (indexPath.row==_selectIndex) {
            [_cell setCellSelected:YES];
        }else{
            [_cell setCellSelected:NO];
        }
        [_cell bindWith:m_arraySorts[indexPath.row]];
        cell=_cell;
    }else{
        YCGoodsSortTableViewCell *_cell = (YCGoodsSortTableViewCell *)[tableView dequeueReusableCellWithIdentifier:YCGoodsSortCellIdentify forIndexPath:indexPath];
        ItemSortTable *sort=m_arraySorts[_selectIndex];
        ItemTable *item=sort.items[indexPath.row];
        [_cell.labTitle setText:item.name];
        [_cell.btnSort setHidden:YES];
        [_cell.lineView setHidden:YES];
        _cell.sortBlock=^(){
            [m_tableView setEditing:YES animated:YES];
        };
        cell=_cell;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView==m_leftTableView) {
        ItemSortTable *selectSort=m_arraySorts[_selectIndex];
        if (_selectArray==selectSort.items) {
            [self saveData:indexPath];
        }else{
            if (m_alertView==nil) {
                m_alertView=[[YCStockAlertView alloc]initWithFrame:CGRectMake(0, 0, kMainScreen_Width, kMainScreen_Height)];
            }
            [m_alertView showSaveAlert:@"是否保存排序?"];
            m_alertView.cancelBlock=^(){
                _selectIndex=indexPath.row;
                [self loadData];
            };
            m_alertView.saveBlock=^(){
                _isSaveBtn=YES;
                [self loadSaveData];
                [self saveData:indexPath];
            };
            [self.view.window addSubview:m_alertView];
        }
    }
}
-(void)saveData:(NSIndexPath *)indexPath
{
    _selectIndex=indexPath.row;
    ItemSortTable *sort=m_arraySorts[_selectIndex];
    [m_leftTableView reloadData];
    
    _selectArray=sort.items;
    m_tableView.layer.shadowPath=nil;
    m_tableView.layer.shadowOpacity=0;
    
    CGFloat tableW=kMainScreen_Width-50-25;
    [m_tableView setFrame:CGRectMake(60, kNAV_HEIGHT+kDistance, tableW, sort.items.count*50)];
    [m_tableView addShadow];
    [m_tableView reloadData];
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    if (sourceIndexPath != destinationIndexPath) {
        ItemSortTable *sort=m_arraySorts[_selectIndex];
        NSMutableArray *array=[NSMutableArray arrayWithArray:sort.items];
        ItemTable  *item= [array objectAtIndex:sourceIndexPath.row];
        [array removeObjectAtIndex:sourceIndexPath.row];
        if (destinationIndexPath.row > [array count]) {
            [array addObject:item];
        }
        else {
            [array insertObject:item atIndex:destinationIndexPath.row];
        }
        sort.items=[NSArray arrayWithArray:array];
    }
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView==m_tableView) {
        if (MODEL_VERSION >= 7.0) {
            if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
            }
            if (MODEL_VERSION >= 8.0) {
                if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
                    [cell setPreservesSuperviewLayoutMargins:NO];
                }
                if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                    [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
                }
            }
        }
    }
}

-(void)btnSaveClicked:(UIButton *)button
{
    ItemSortTable *sort=m_arraySorts[_selectIndex];
    if (sort.items.count==0) {
        return;
    }
    _isSaveBtn=YES;
    [self loadSaveData];
}
-(void)loadSaveData
{
    ItemSortTable *sort=m_arraySorts[_selectIndex];
    NSMutableArray *arrayIds=[NSMutableArray array];
    for (ItemTable *item in sort.items) {
        [arrayIds addObject:item.Id];
    }
    NSString *idString=[arrayIds componentsJoinedByString:@";"];
    ShopItemSortRequest *request = [ShopItemSortRequest new];
    request.item_ids=[NSString stringWithFormat:@"%@;",idString];
    [apiClient hideProgress];
    [apiClient doShopItemSort:request success:^(ApiResponse *data, NSString *url) {
        [self.view showHUD:data.message];
        [self loadData];
        
        self.sortBlock();
        if (!_isSaveBtn) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }failure:^(ApiResponse *data, NSString *url){
    }];
}


@end
